package com.zmn.oms.third.guomei.service.impl;

import com.alibaba.fastjson.JSON;
import com.site.lookup.util.StringUtils;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.model.entity.notifylog.OrderNotifyLog;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.model.vo.remark.OrderRemarkDetailVO;
import com.zmn.oms.model.vo.remark.OrderRemarkVO;
import com.zmn.oms.model.vo.work.modify.amount.ZsServiceItemVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.base.util.AESUtil;
import com.zmn.oms.third.base.util.MasterPhoneUtil;
import com.zmn.oms.third.gomegj.GmgjConsts;
import com.zmn.oms.third.gomegj.GmgjUtil;
import com.zmn.oms.third.gomegj.api.GmgjOrderServicePlan;
import com.zmn.oms.third.gomegj.api.GmgjSyncOrderSeriveRequest;
import com.zmn.oms.third.gomegj.service.GmgjService;
import com.zmn.oms.third.guomei.GmqxConsts;
import com.zmn.oms.third.guomei.GmqxUtil;
import com.zmn.oms.third.guomei.dto.*;
import com.zmn.oms.third.guomei.dto.api.*;
import com.zmn.oms.zmn.business.interfaces.open.OrderChangeNotifyService;
import com.zmn.oms.zmn.business.interfaces.open.OrderNewNotifyService;
import com.zmn.oms.zmn.normal.business.interfaces.serviceitem.ZsNormalOrderServiceItemBService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 类描述：向58到家直约推送订单变化通知的服务
 *
 * @author XieWenBing
 * @date 2019/12/03 18:00
 */

@Slf4j
@Service("gmqxNotifyService")
public class GmqxNotifyServiceImpl implements OrderChangeNotifyService, OrderNewNotifyService {

    @Autowired
    private OrderNotifyLogBService orderNotifyLogBService;

    @Autowired
    private GmgjService gmgjService;

    @Autowired
    private OrderWorkService orderWorkService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderRemarkBService orderRemarkBService;

    @Autowired
    private OrderExtendService orderExtendService;

    @Override
    public void notifyChange(OrderWorkLogChange orderWorkLogChange) {
        // 判断功能是否开启
        if (!GmqxConsts.POWER_ON) {
            log.info("【{}】<订单状态同步> 该功能没有开启。", GmqxConsts.CHANNEL_NAME);
            return;
        }

        // 参数判断
        if (Objects.isNull(orderWorkLogChange)) {
            log.info("【{}】<订单状态同步> - orderWorkLogChange参数为空。", GmqxConsts.CHANNEL_NAME);
            return;
        }

        log.info("【{}】<订单状态同步> ,状态信息:[{}]。", GmqxConsts.CHANNEL_NAME, orderWorkLogChange.toString());

        int logType = orderWorkLogChange.getLogType().intValue();

        try {
            switch (logType) {
                // 针对首次同步接单失败的情况，可通过“修改”操作，再次触发同步接单状态
                case OrderLogConsts.ORDER_LOG_TYPE_INPUT:
                    this.sendCreateOrderToGuomeiQingxi(orderWorkLogChange);
                    break;
                // 修改/确认
                case OrderLogConsts.ORDER_LOG_TYPE_UPDATE:
                case OrderLogConsts.ORDER_LOG_TYPE_CONFIRM:
                case OrderLogConsts.ORDER_LOG_TYPE_MASTER_MODIFY_DUTY_TIME:
                    this.sendCreateOrderToGuomeiQingxi(orderWorkLogChange);
                    this.sendChangeDutyTimeToGuomeiQingxi(orderWorkLogChange);
                    break;
                // 派单
                case OrderLogConsts.ORDER_LOG_TYPE_DISTRIBUTE:
                    this.sendUpdateOrderToGuomeiQingxi(orderWorkLogChange);
                    break;
                // 工程师上门
                case OrderLogConsts.ORDER_LOG_TYPE_VISIT:
                    this.sendBeginServiceToGuomeiQingxi(orderWorkLogChange);
                    break;
                case OrderLogConsts.ORDER_LOG_TYPE_SERVICEITEM:
                    // 修改服务项
                    this.syncOrderServiceItem(orderWorkLogChange);
                    break;
                // 取消、失败、弃单
                case OrderLogConsts.ORDER_LOG_TYPE_CANCEL:
                case OrderConsts.ORDER_OP_TYPE_FAIL:
                case OrderConsts.ORDER_OP_TYPE_DISCARD:
                    this.sendCancelOrderToGuomeiQingxi(orderWorkLogChange);
                    break;
                // 完成
                case OrderLogConsts.ORDER_LOG_TYPE_COMPLETE:
                    this.sendFinishOrderToGuomeiQingxi(orderWorkLogChange);
                    break;
                default:
                    return;
            }
        } catch (OmsBaseException e) {
            log.info("【{}】<订单状态同步>失败，订单状态为:[{}]，提示消息:[{}]。", GmqxConsts.CHANNEL_NAME, logType, e.getMessage());
        }

        log.info("【{}】<订单状态同步完成> ", GmqxConsts.CHANNEL_NAME);
    }

    @Override
    public void notifyNewOrder(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {
        // 判断功能是否开启
        if (!GmqxConsts.POWER_ON) {
            log.info("【{}】<订单状态同步-新订单> 该功能没有开启。", GmqxConsts.CHANNEL_NAME);
            return;
        }

        // 参数判断
        if (Objects.isNull(orderWorkLogChange)) {
            log.info("【{}】<订单状态同步> - orderWorkLogChange参数为空。", GmqxConsts.CHANNEL_NAME);
            return;
        }

        // 同步创建订单消息给国美美云保清洗平台
        try {
            log.info("【{}】<订单状态同步-新订单>,订单状态:[{}] ", GmqxConsts.CHANNEL_NAME, orderWorkLogChange.toString());
            this.sendCreateOrderToGuomeiQingxi(orderWorkLogChange);
        } catch (OmsBaseException e) {
            log.info("【{}】<订单状态同步-新订单>失败。", GmqxConsts.CHANNEL_NAME);
        }
    }

    /**
     * 发送给国美美云保清洗 同步创建订单消息
     *
     * @param orderWorkLogChange
     * @author xiewenbing
     */
    private void sendCreateOrderToGuomeiQingxi(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 查看同步记录，对已经同步接单成功的，不需要再次同步
        if (this.findSaveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_INPUT)) {
            return;
        }

        String outerId = orderWorkLogChange.getOuterId();
        // 判断外部订单单id
        if (StringUtil.isNullOrEmpty(outerId)) {
            throw new OmsBaseException("消息通知参数错误-没有对应的外部订单Id");
        }

        // 填充发送信息
        GmqxSyncCreateOrderDTO createOrderDTO = new GmqxSyncCreateOrderDTO();
        GmqxSyncCreateOrderItem createOrderItem = new GmqxSyncCreateOrderItem();
        List<GmqxSyncCreateOrderItem> createOrderItems = new LinkedList<>();

        createOrderDTO.setOrderId(outerId);
        createOrderItem.setGjOrderId(String.valueOf(orderWorkLogChange.getOrderId()));
        createOrderItem.setOrderSubId(getGuomeiOrderSubId(orderWorkLogChange.getOrderId(), outerId));
        createOrderItems.add(createOrderItem);
        createOrderDTO.setItems(createOrderItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_ORDER_CREATE);
        syncRequestDTO.setData(JSON.toJSONString(createOrderDTO));

        GmqxResultDTO resultDTO = this.sendSyncOrderMessage(syncRequestDTO);
        if (Objects.isNull(resultDTO)) {
            throw new OmsBaseException("发送订单创建消息失败");
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            String resultMsg = StringUtil.isNullOrEmpty(resultDTO.getResult().getMsg()) ? "" : resultDTO.getResult().getMsg();
            log.info("[{}] 同步订单创建消息失败，返回的消息提示:[{}]", GmqxConsts.CHANNEL_NAME, resultMsg);
        } else {
            log.info("[{}] 同步订单创建消息成功", GmqxConsts.CHANNEL_NAME);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_INPUT, resultDTO);

        return;
    }

    /**
     * 发送给国美美云保清洗 同步预约时间消息
     *
     * @param orderWorkLogChange
     * @author xiewenbing
     */
    private void sendChangeDutyTimeToGuomeiQingxi(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // ‘修改’ 和 ‘确认’时，如果dutytime为null，则表示没有修改预约时间
        if (Objects.isNull(orderWorkLogChange.getDutyTime())) {
            return;
        }

        String outerId = orderWorkLogChange.getOuterId();
        // 判断外部订单单id
        if (StringUtil.isNullOrEmpty(outerId)) {
            throw new OmsBaseException("消息通知参数错误-没有对应的外部订单Id");
        }

        // 填充发送信息
        GmqxSyncDutytimeDTO dutytimeDTO = new GmqxSyncDutytimeDTO();
        GmqxSyncDutytimeItem dutytimeItem = new GmqxSyncDutytimeItem();
        List<GmqxSyncDutytimeItem> dutytimeItems = new LinkedList<>();

        dutytimeDTO.setOrderId(outerId);
        dutytimeItem.setGjOrderId(String.valueOf(orderWorkLogChange.getOrderId()));
        dutytimeItem.setOrderSubId(getGuomeiOrderSubId(orderWorkLogChange.getOrderId(), outerId));

        Date dutyTime = orderWorkLogChange.getDutyTime();
        DateFormat dutyDateFormate = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat dutyTimeFormate = new SimpleDateFormat("hh:mm:ss");
        String strDutyDate = dutyDateFormate.format(dutyTime);
        String strDutyTime = dutyTimeFormate.format(dutyTime);

        dutytimeItem.setAppointmentDate(dutyDateFormate.parse(strDutyDate, new ParsePosition(0)));
        dutytimeItem.setStartTime(strDutyTime);
        dutytimeItem.setEndTime(strDutyTime);

        dutytimeItems.add(dutytimeItem);
        dutytimeDTO.setItems(dutytimeItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_DUTY_TIME);
        syncRequestDTO.setData(JSON.toJSONString(dutytimeDTO));

        GmqxResultDTO resultDTO = this.sendSyncOrderMessage(syncRequestDTO);
        if (Objects.isNull(resultDTO)) {
            throw new OmsBaseException("发送订单预约时间消息失败");
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            String resultMsg = StringUtil.isNullOrEmpty(resultDTO.getResult().getMsg()) ? "" : resultDTO.getResult().getMsg();
            log.info("[{}] 同步订单预约时间消息失败，返回的消息提示:[{}]", GmqxConsts.CHANNEL_NAME, resultMsg);
        } else {
            log.info("[{}] 同步订单预约时间消息成功", GmqxConsts.CHANNEL_NAME);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CONFIRM, resultDTO);
    }

    /**
     * 发送给国美美云保清洗 同步派单消息
     *
     * @param orderWorkLogChange
     * @author xiewenbing
     */
    private void sendUpdateOrderToGuomeiQingxi(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        String outerId = orderWorkLogChange.getOuterId();
        // 判断外部订单单id
        if (StringUtil.isNullOrEmpty(outerId)) {
            throw new OmsBaseException("消息通知参数错误-没有对应的外部订单Id");
        }

        // 获取工单信息
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderWorkLogChange.getOrderId(), orderWorkLogChange.getWorkId());
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查不到对应的工单信息");
        }

        // 填充发送信息
        GmqxSyncOrderStatusDTO orderStatusDTO = new GmqxSyncOrderStatusDTO();
        GmqxSyncOrderStatusItem orderStatusItem = new GmqxSyncOrderStatusItem();
        List<GmqxSyncOrderStatusItem> orderStatusItems = new LinkedList<>();

        orderStatusDTO.setOrderId(outerId);
        orderStatusDTO.setOrderSubId(getGuomeiOrderSubId(orderWorkLogChange.getOrderId(), outerId));
        orderStatusItem.setGjOrderId(String.valueOf(orderWorkLogChange.getOrderId()));
        orderStatusItem.setOrderStatus(GmqxConsts.ORDER_STATUS_CODE_DISTRIBUTE);
        orderStatusItem.setEngineerName(
                Optional.ofNullable(orderWork.getMasterName())
                        .filter(name -> name.length() >= 1)
                        .map(name -> String.format("%s工程师", name.substring(0, 1)))
                        .orElse("工程师")
        );
        orderStatusItem.setEngineerPhone(
                Optional.ofNullable(orderDetailService.findOrderDetailByKey(orderWork.getOrderId()))
                        .map(orderDetail -> {
                            if (Objects.equals(orderDetail.getBindStatus(), OrderConsts.BIND_STATUS_BIND)
                                    && org.apache.commons.lang3.StringUtils.isNotBlank(orderDetail.getBindTelephone())) {
                                return orderDetail.getBindTelephone();
                            }
                            return null;
                        })
                        .orElse(MasterPhoneUtil.getSafeMasterPhone(orderWork.getCityId()))
        );

        orderStatusItems.add(orderStatusItem);
        orderStatusDTO.setItems(orderStatusItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_ORDER_STATUS);
        syncRequestDTO.setData(JSON.toJSONString(orderStatusDTO));

        GmqxResultDTO resultDTO = this.sendSyncOrderMessage(syncRequestDTO);
        if (Objects.isNull(resultDTO)) {
            throw new OmsBaseException("发送派单消息失败");
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            String resultMsg = StringUtil.isNullOrEmpty(resultDTO.getResult().getMsg()) ? "" : resultDTO.getResult().getMsg();
            log.info("[{}] 同步派单消息失败，返回的消息提示:[{}]", GmqxConsts.CHANNEL_NAME, resultMsg);
        } else {
            log.info("[{}] 同步派单消息成功", GmqxConsts.CHANNEL_NAME);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_DISTRIBUTE, resultDTO);
    }

    /**
     * 发送给国美美云保清洗 同步工程师上门消息
     *
     * @param orderWorkLogChange
     * @author xiewenbing
     */
    private void sendBeginServiceToGuomeiQingxi(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        String outerId = orderWorkLogChange.getOuterId();
        // 判断外部订单单id
        if (StringUtil.isNullOrEmpty(outerId)) {
            throw new OmsBaseException("消息通知参数错误-没有对应的外部订单Id");
        }

        // 填充发送信息
        GmqxSyncOrderStatusDTO orderStatusDTO = new GmqxSyncOrderStatusDTO();
        GmqxSyncOrderStatusItem orderStatusItem = new GmqxSyncOrderStatusItem();
        List<GmqxSyncOrderStatusItem> orderStatusItems = new LinkedList<>();

        orderStatusDTO.setOrderId(outerId);
        orderStatusDTO.setOrderSubId(getGuomeiOrderSubId(orderWorkLogChange.getOrderId(), outerId));
        orderStatusItem.setGjOrderId(String.valueOf(orderWorkLogChange.getOrderId()));
        orderStatusItem.setOrderStatus(GmqxConsts.ORDER_STATUS_CODE_VISIT);
        orderStatusItem.setEngineerName("");
        orderStatusItem.setEngineerPhone("");

        orderStatusItems.add(orderStatusItem);
        orderStatusDTO.setItems(orderStatusItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_ORDER_STATUS);
        syncRequestDTO.setData(JSON.toJSONString(orderStatusDTO));

        GmqxResultDTO resultDTO = this.sendSyncOrderMessage(syncRequestDTO);
        if (Objects.isNull(resultDTO)) {
            throw new OmsBaseException("发送工程师上门消息失败");
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            String resultMsg = StringUtil.isNullOrEmpty(resultDTO.getResult().getMsg()) ? "" : resultDTO.getResult().getMsg();
            log.info("[{}] 同步工程师上门消息失败，返回的消息提示:[{}]", GmqxConsts.CHANNEL_NAME, resultMsg);
        } else {
            log.info("[{}] 同步工程师上门消息成功", GmqxConsts.CHANNEL_NAME);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_VISIT, resultDTO);
    }

    /**
     * 发送给国美美云保清洗 同步取消订单消息
     *
     * @param orderWorkLogChange
     * @author xiewenbing
     */
    private void sendCancelOrderToGuomeiQingxi(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 判断是否为国美美云保平台取消的订单，是则不处理
        if ((orderWorkLogChange.getOperatorId() == OrderConsts.CHANNEL_ID_GUOMEI_MYBQX) &&
                (orderWorkLogChange.getOperatorType() == GlobalConsts.OPERATE_USER_TYPE_CHANNEL)) {
            return;
        }

        String outerId = orderWorkLogChange.getOuterId();
        // 判断外部订单单id
        if (StringUtil.isNullOrEmpty(outerId)) {
            throw new OmsBaseException("消息通知参数错误-没有对应的外部订单Id");
        }

        // 填充发送信息
        GmqxSyncCancelOrderDTO cancelOrderDTO = new GmqxSyncCancelOrderDTO();
        GmqxSyncCancelOrderItem cancelOrderItem = new GmqxSyncCancelOrderItem();
        List<GmqxSyncCancelOrderItem> cancelOrderItems = new LinkedList<>();

        cancelOrderDTO.setOrderId(outerId);
        cancelOrderDTO.setOrderSubId(getGuomeiOrderSubId(orderWorkLogChange.getOrderId(), outerId));
        cancelOrderItem.setGjOrderId(String.valueOf(orderWorkLogChange.getOrderId()));
        cancelOrderItem.setReason(this.getOrderCancelReason(orderWorkLogChange.getOrderId(), orderWorkLogChange.getWorkId()));
        cancelOrderItems.add(cancelOrderItem);
        cancelOrderDTO.setItems(cancelOrderItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_CANCEL_ORDER);
        syncRequestDTO.setData(JSON.toJSONString(cancelOrderDTO));

        GmqxResultDTO resultDTO = this.sendSyncOrderMessage(syncRequestDTO);
        if (Objects.isNull(resultDTO)) {
            throw new OmsBaseException("发送取消订单消息失败");
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            String resultMsg = StringUtil.isNullOrEmpty(resultDTO.getResult().getMsg()) ? "" : resultDTO.getResult().getMsg();
            log.info("[{}] 同步取消订单消息失败，返回的消息提示:[{}]", GmqxConsts.CHANNEL_NAME, resultMsg);
        } else {
            log.info("[{}] 同步取消订单消息成功", GmqxConsts.CHANNEL_NAME);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CANCEL, resultDTO);
    }

    /**
     * 发送给国美美云保清洗 同步订单完成消息
     *
     * @param orderWorkLogChange
     * @author xiewenbing
     */
    private void sendFinishOrderToGuomeiQingxi(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 判断外部订单单id
        String outerId = orderWorkLogChange.getOuterId();
        if (StringUtil.isNullOrEmpty(outerId)) {
            throw new OmsBaseException("消息通知参数错误-没有对应的外部订单Id");
        }

        // 获取工单信息
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderWorkLogChange.getOrderId(), orderWorkLogChange.getWorkId());
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查不到对应的工单信息");
        }

        // 填充发送信息
        GmqxSyncOrderFinishDTO orderFinishDTO = new GmqxSyncOrderFinishDTO();
        GmqxSyncOrderFinishItem orderFinishItem = new GmqxSyncOrderFinishItem();
        List<GmqxSyncOrderFinishItem> orderFinishItems = new LinkedList<>();

        orderFinishDTO.setOrderId(outerId);
        orderFinishDTO.setOrderSubId(getGuomeiOrderSubId(orderWorkLogChange.getOrderId(), outerId));
        orderFinishItem.setGjOrderId(String.valueOf(orderWorkLogChange.getOrderId()));

        Date completeTime = orderWork.getCompleteTime();
        orderFinishItem.setCompleteTime(Objects.isNull(completeTime) ? new Date() : completeTime);

        orderFinishItems.add(orderFinishItem);
        orderFinishDTO.setItems(orderFinishItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_ORDER_FINISH);
        syncRequestDTO.setData(JSON.toJSONString(orderFinishDTO));

        GmqxResultDTO resultDTO = this.sendSyncOrderMessage(syncRequestDTO);
        if (Objects.isNull(resultDTO)) {
            throw new OmsBaseException("发送订单完成消息失败");
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            String resultMsg = StringUtil.isNullOrEmpty(resultDTO.getResult().getMsg()) ? "" : resultDTO.getResult().getMsg();
            log.info("[{}] 同步订单完成消息失败，返回的消息提示:[{}]", GmqxConsts.CHANNEL_NAME, resultMsg);
        } else {
            log.info("[{}] 同步订单完成消息成功", GmqxConsts.CHANNEL_NAME);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_COMPLETE, resultDTO);
    }


    /**
     * 发送给国美美云保清洗 同步订单的消息（创建订单，取消订单，订单状态，预约时间，订单完成等）
     *
     * @param requestDTO
     * @return GmqxResultDTO
     * @author xiewenbing
     */
    private GmqxResultDTO sendSyncOrderMessage(GmqxSyncRequestDTO requestDTO) throws OmsBaseException {

        // 参数判断
        if (Objects.isNull(requestDTO) || StringUtil.isNullOrEmpty(requestDTO.getData())) {
            throw new OmsBaseException("传入的数据不正确");
        }

        // 加密数据，生成msgId
        requestDTO.setMsgId(getMsgId());

        log.info("[{}] 加密前消息内容为[{}]", GmqxConsts.CHANNEL_NAME, requestDTO.getData());

        String requestBody = AESUtil.encrypt(requestDTO.getData(), GmqxConsts.AES_KEY);
        if (StringUtil.isNullOrEmpty(requestBody)) {
            throw new OmsBaseException("数据加密失败");
        }
        requestDTO.setData(requestBody);

        log.info("[{}] 加密后消息内容为[{}]", GmqxConsts.CHANNEL_NAME, requestDTO.getData());
        return GmqxUtil.sendRequstToGuomeiQingxi(requestDTO);
    }

    /**
     * 根据时间生成消息Id
     *
     * @return String
     */
    private String getMsgId() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String msgId = "GMQX" + simpleDateFormat.format(new Date());

        return msgId;
    }

    /**
     * 保存状态同步结果信息
     *
     * @param orderWorkLogChange
     * @param orderStatus
     * @param result
     */
    private void saveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus, GmqxResultDTO result) {
        if (Objects.isNull(result) || Objects.isNull(orderWorkLogChange)) {
            return;
        }

        OrderNotifyLog orderNotifyLog = new OrderNotifyLog();
        orderNotifyLog.setMqMsgKey(orderWorkLogChange.getMqMsgKey());
        orderNotifyLog.setOrderId(orderWorkLogChange.getOrderId());
        orderNotifyLog.setChannelId(orderWorkLogChange.getChannelId());
        orderNotifyLog.setOrderStatus(orderWorkLogChange.getStatus());
        orderNotifyLog.setOrderResultStatus(orderWorkLogChange.getResultStatus());
        orderNotifyLog.setNotifyStatus(String.valueOf(orderStatus));
        orderNotifyLog.setType(OrderConsts.ORDER_NOTIFY_TYPE_CHANGE);
        orderNotifyLog.setNotifyTime(DateUtil.getNow());

        String resultMsg = result.getResult().getMsg();
        orderNotifyLog.setNotifyResultMsg(String.format("[%s]-%s",
                OrderStatusConsts.getOrderStatusName(orderStatus), StringUtil.isNullOrEmpty(resultMsg) ? "" : resultMsg));

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setStatus(result.getResult().getCode() == GmqxConsts.RESPONSE_CODE_SUCCESS ? StatusConsts.STATUS_SUCCESS : StatusConsts.STATUS_ERROR);
        resultDTO.setData(orderNotifyLog);

        orderNotifyLogBService.saveNotifyLog(resultDTO);
    }

    /**
     * 查询状态同步结果信息
     *
     * @param orderWorkLogChange
     * @param orderStatus
     * @return boolean
     */
    private boolean findSaveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus) {

        // 根据订单id查找保存的是数据
        Long orderId = orderWorkLogChange.getOrderId();
        List<OrderNotifyLog> orderNotifyLogs = orderNotifyLogBService.listByOrderId(orderId);
        if (Objects.isNull(orderNotifyLogs)) {
            return false;
        }

        for (OrderNotifyLog item : orderNotifyLogs) {
            if (Objects.equals(String.valueOf(orderStatus), item.getNotifyStatus())
                    && Objects.equals(StatusConsts.STATUS_SUCCESS, item.getNotifyResultStatus())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 查询国美美云保的子订单号
     *
     * @param orderId
     * @return String
     */
    private String getGuomeiOrderSubId(Long orderId, String outerId) {
        if (NumberUtil.isNullOrZero(orderId)) {
            return outerId;
        }

        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
        if (Objects.isNull(orderExtend)) {
            return outerId;
        }

        GmqxOrderOutData orderOutData = JSON.parseObject(orderExtend.getOuterData(), GmqxOrderOutData.class);
        if (Objects.isNull(orderOutData)) {
            return outerId;
        }

        return StringUtil.isNullOrEmpty(orderOutData.getOrderSubId()) ? outerId : orderOutData.getOrderSubId();
    }

    /**
     * 获取订单取消的原因
     *
     * @param orderId
     * @param workId
     * @return String
     */
    protected String getOrderCancelReason(Long orderId, Long workId) {

        String cancelReason = "";

        do {
            OrderRemarkVO orderRemarkVO = orderRemarkBService.findOrderRemarkVO(orderId, workId, OrderConsts.ORDER_REMARK_TYPE_CANCEL);
            if (Objects.isNull(orderRemarkVO)) {
                break;
            }

            if (StringUtils.isNotEmpty(orderRemarkVO.getContent())) {
                cancelReason = orderRemarkVO.getContent();
            }

            if (CollectionUtil.isNullOrEmpty(orderRemarkVO.getDetailVOList())) {
                break;
            }

            for (OrderRemarkDetailVO item : orderRemarkVO.getDetailVOList()) {
                if (StringUtils.isNotEmpty(item.getMapName())) {
                    if (StringUtils.isNotEmpty(cancelReason)) {
                        cancelReason += ";";
                    }

                    cancelReason += item.getMapName();
                }
            }
        } while (false);

        return cancelReason.isEmpty() ? "订单被平台取消" : cancelReason;
    }

    protected void syncOrderServiceItem(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 订单查找
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderWorkLogChange.getOrderId(),
                orderWorkLogChange.getWorkId());
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查找不到对应的订单");
        }
        String accessToken = gmgjService.getAccessToken();
        log.info("国美修改服务项调用同步服务项接口入参,accessToken:{},orderWork:{}", accessToken, orderWork);
        gmgjService.syncOrderServiceItem(accessToken, orderWork);
    }


    /**
     * 测试代码
     *
     * @param args
     */
    public static void main(String[] args) {

        GmqxSyncOrderFinishDTO orderFinishDTO = new GmqxSyncOrderFinishDTO();
        GmqxSyncOrderFinishItem orderFinishItem = new GmqxSyncOrderFinishItem();
        List<GmqxSyncOrderFinishItem> orderFinishItems = new LinkedList<>();

        String outerId = "QX10501575875387473011";
        orderFinishDTO.setOrderId(outerId);
        orderFinishDTO.setOrderSubId(outerId);
        orderFinishItem.setGjOrderId("410814410672582656");

        Date completeTime = new Date();
        orderFinishItem.setCompleteTime(Objects.isNull(completeTime) ? new Date() : completeTime);

        orderFinishItems.add(orderFinishItem);
        orderFinishDTO.setItems(orderFinishItems);

        GmqxSyncRequestDTO syncRequestDTO = new GmqxSyncRequestDTO();
        syncRequestDTO.setMethod(GmqxConsts.METHOD_SYNC_ORDER_FINISH);
        syncRequestDTO.setData(JSON.toJSONString(orderFinishDTO));

        // 加密数据，生成msgId
        syncRequestDTO.setMsgId("GMQX20191209183455348");

        log.info("[{}] 加密前消息内容为[{}]", GmqxConsts.CHANNEL_NAME, syncRequestDTO.getData());

        String requestBody = AESUtil.encrypt(syncRequestDTO.getData(), GmqxConsts.AES_KEY);
        if (StringUtil.isNullOrEmpty(requestBody)) {
            return;
        }
        syncRequestDTO.setData(requestBody);

        log.info("[{}] 加密后消息内容为[{}]", GmqxConsts.CHANNEL_NAME, syncRequestDTO.getData());

        if (!GmqxUtil.makeRequestSign(syncRequestDTO)) {
            log.info("【{}-API】 发送请求失败:生成签名失败", GmqxConsts.CHANNEL_NAME);
            return;
        }

        String pathRequst = String.format("method=%s&msgId=%s&sign=%s", syncRequestDTO.getMethod(), syncRequestDTO.getMsgId(), syncRequestDTO.getSign());
        String urlRequest = "https://msc-dev.meinstech.com/gome/clean/guanjiaInterface?" + pathRequst;
        String httpResponse;

        try {
            log.info("【{}-API】<API请求> Url:[{}] RequestBody:[{}]", GmqxConsts.CHANNEL_NAME, urlRequest, syncRequestDTO.getData());

            httpResponse = HttpUtil.httpsPost(urlRequest, syncRequestDTO.getData());

            log.info("【{}-API】<API响应> ResponseBody:[{}]", GmqxConsts.CHANNEL_NAME, httpResponse);

        } catch (Exception e) {
            log.info("【{}-API】 请求失败:[{}]", GmqxConsts.CHANNEL_NAME, Objects.nonNull(e) ? e.getMessage() : "");
            if (Objects.nonNull(e)) {
                log.error(e.toString());
            }

            return;
        }

        GmqxResultDTO resultDTO = JSON.parseObject(httpResponse, GmqxResultDTO.class);
        if (Objects.isNull(resultDTO)) {
            log.info("【{}-API】 解析返回数据失败", GmqxConsts.CHANNEL_NAME);
            return;
        }

        if (resultDTO.getResult().getCode() != GmqxConsts.RESPONSE_CODE_SUCCESS) {
            log.info("【{}-API】 返回提示错误，错误代码:[{}]，错误提示消息:[{}]", GmqxConsts.CHANNEL_NAME,
                    resultDTO.getResult().getCode(),
                    resultDTO.getResult().getMsg());
        }
    }
}
